package com.gitee.wsl.data.savable

import com.gitee.wsl.Lib
import com.gitee.wsl.ext.json.defaultJson
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import kotlin.reflect.KType


class JsonStateSaver(
    private val json: Json = Lib.defaultJson,
    private val map: MutableMap<String, String>
) : Savable {

    override fun <T> saveState(key: String, kType: KType, value: T?) {
        if (value != null) {
            try {
                val serializer = json.serializersModule.serializer(kType) as KSerializer<T>
                map[key] = json.encodeToString(serializer, value)
            } catch (e: SerializationException) {
                // Workaround for JS and Native https://github.com/Kotlin/kotlinx.serialization/issues/1077

                throw e
            }
        } else {
            map.remove(key)
        }
    }

    override fun <T> restoreState(key: String, kType: KType): T? {
        return map[key]?.let { jsonString ->
            try {
                val serializer = json.serializersModule.serializer(kType) as KSerializer<T>
                return json.decodeFromString(serializer, jsonString)
            } catch (e: SerializationException) {

                throw e
            }
        }
    }
}